import sys
from core import *
#from agents import agent_classes, Random
from operator import attrgetter
from optparse import OptionParser
import logging

class LogToText(logging.Handler):
    def emit(self, record):
        print self.format(record)
    
class IDSGConsole(object):
    def __init__(self):
        # prepare logging handler
        logger=logging.getLogger()
        logger.setLevel(logging.DEBUG)
        handler = LogToText()
        formatter = logging.Formatter('%(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)

        # prepare usage message
        usage = '%prog [t/g] ("t" for tournament mode or "g" for single game mode)'
        parser = OptionParser(usage.rstrip('\n'),version="IDS simulator v0.1")
        parser.add_option("-r", "--num_rounds", type="int", dest="num_rounds", default=10)
        parser.add_option("-t", "--tourament_iterations", type="int", dest="iterations", default=200)
        parser.add_option("-s", "--start_balance", type="float", dest="start_balance", default=0)
        parser.add_option("-i", "--cost_of_investing", type="float", dest="cost_of_investing", default=-12)
        parser.add_option("-n", "--cost_of_negevent", type="float", dest="cost_of_negevent", default=-50)
        parser.add_option("-p", "--p", type="float", dest="p", default=0.2)
        parser.add_option("-g", "--graph_type", type="string", dest="graph_type", default='complete')
        parser.add_option("-c", "--correlated_outcomes", action="store_true", dest="correlated_outcomes", default=True)
        parser.add_option("-u", "--uncorrelated_outcomes", action="store_false", dest="correlated_outcomes", default=True)
        opt, args = parser.parse_args()
        if len(args) != 1 or args[0].lower() not in ['t','g']:
            parser.print_help()
            sys.exit(2)
        # run simulation
        world = World(start_balance=opt.start_balance, cost_of_investing=opt.cost_of_investing,
                      cost_of_negevent=opt.cost_of_negevent, p=opt.p, graph_type=opt.graph_type,
                      num_rounds=opt.num_rounds, correlated_outcomes=opt.correlated_outcomes)
        am = AgentManager()
        if args[0].lower() == 't':
            # tournament mode
            t = Tournament(AgentSet(am.classes()),world,opt.iterations)
            t.run()
        elif args[0].lower() == 'g':
            # game mode
            agents = [am['Random']() for i in range(2)]
            #world.setup_agents(agents)
            g = Game(agents,world,plots=True)
            g.play()

if __name__ == "__main__":
    IDSGConsole()